package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.utils.http.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TlDyCategoryMapper;
import com.ruoyi.common.core.domain.entity.TlDyCategory;
import com.ruoyi.system.service.ITlDyCategoryService;

/**
 * 抖音类目Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-21
 */
@Service
public class TlDyCategoryServiceImpl implements ITlDyCategoryService
{
    @Autowired
    private TlDyCategoryMapper tlDyCategoryMapper;
    @Value("${ruoyi.dyAppid}")
    private String  dyAppid;
    @Value("${ruoyi.dySecretKey}")
    private String  dySecretKey;

    /**
     * 查询抖音类目
     *
     * @param id 抖音类目主键
     * @return 抖音类目
     */
    @Override
    public TlDyCategory selectTlDyCategoryById(Long id)
    {
        return tlDyCategoryMapper.selectTlDyCategoryById(id);
    }

    /**
     * 查询抖音类目列表
     *
     * @param tlDyCategory 抖音类目
     * @return 抖音类目
     */
    @Override
    public List<TlDyCategory> selectTlDyCategoryList(TlDyCategory tlDyCategory)
    {
        return tlDyCategoryMapper.selectTlDyCategoryList(tlDyCategory);
    }

    /**
     * 新增抖音类目
     *
     * @param tlDyCategory 抖音类目
     * @return 结果
     */
    @Override
    public int insertTlDyCategory(TlDyCategory tlDyCategory)
    {
        return tlDyCategoryMapper.insertTlDyCategory(tlDyCategory);
    }

    /**
     * 修改抖音类目
     *
     * @param tlDyCategory 抖音类目
     * @return 结果
     */
    @Override
    public int updateTlDyCategory(TlDyCategory tlDyCategory)
    {
        return tlDyCategoryMapper.updateTlDyCategory(tlDyCategory);
    }

    /**
     * 批量删除抖音类目
     *
     * @param ids 需要删除的抖音类目主键
     * @return 结果
     */
    @Override
    public int deleteTlDyCategoryByIds(Long[] ids)
    {
        return tlDyCategoryMapper.deleteTlDyCategoryByIds(ids);
    }

    /**
     * 删除抖音类目信息
     *
     * @param id 抖音类目主键
     * @return 结果
     */
    @Override
    public int deleteTlDyCategoryById(Long id)
    {
        return tlDyCategoryMapper.deleteTlDyCategoryById(id);
    }

    @Override
    public List<TreeSelect> buildCategoryTreeSelect(List<TlDyCategory> tlDyCategories) {
        List<TlDyCategory> tlDyCategoryList = buildCategoryTree(tlDyCategories);
        return tlDyCategoryList.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public int syncDyCategory() {
        //获取抖音分类信息
        String get = HttpUtils.sendPost("http://api.zcxq.cn/open/goods/category/", "app_id=" + dyAppid + "&sec=" + dySecretKey );
        JSONObject jsonObject =  JSONObject.parseObject(get);
        String code = jsonObject.getString("code");
        if(!code.equals("200")){
            return 0;
        }
        String data = jsonObject.getString("data");
        JSONObject jsonData =  JSONObject.parseObject(data);
        List<TlDyCategory> inserts = new ArrayList<>();
        // 遍历键和值
        for (String key : jsonData.keySet()) {
            String value = jsonData.getString(key);
            JSONObject valueData = JSONObject.parse(value);
            TlDyCategory tlDyCategory = new TlDyCategory();
            tlDyCategory.setParentId(0L);
            tlDyCategory.setDyCategoryName(key);
            tlDyCategory.setDyCategoryId(Long.parseLong(valueData.get("id").toString()));
            tlDyCategory.setId(tlDyCategory.getDyCategoryId());
            //一级分类
            inserts.add(tlDyCategory);
            //二级分类
            String dycatids = valueData.getString("dycatids");
            String[] split = dycatids.split(",");
            for(int i=0;i<split.length;i++){
                TlDyCategory erjitlDyCategory = new TlDyCategory();
                erjitlDyCategory.setDyCategoryId(Long.parseLong(split[i]));
                erjitlDyCategory.setParentId(tlDyCategory.getDyCategoryId());
                erjitlDyCategory.setDyCategoryName(split[i]);
                inserts.add(erjitlDyCategory);
            }
        }
        tlDyCategoryMapper.deleteTlDyCategoryAll();
        for (TlDyCategory tlDyCategory:inserts) {
            tlDyCategoryMapper.insertTlDyCategory(tlDyCategory);
        }
        return 1;
    }

    public List<TlDyCategory> buildCategoryTree(List<TlDyCategory> dyCategories)
    {
        List<TlDyCategory> returnList = new ArrayList<TlDyCategory>();
        List<Long> tempList = dyCategories.stream().map(TlDyCategory::getId).collect(Collectors.toList());
        for (Iterator<TlDyCategory> iterator = dyCategories.iterator(); iterator.hasNext();)
        {
            TlDyCategory tlDyCategory = (TlDyCategory) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(tlDyCategory.getParentId()))
            {
                recursionFn(dyCategories, tlDyCategory);
                returnList.add(tlDyCategory);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = dyCategories;
        }
        return returnList;
    }

    private void recursionFn(List<TlDyCategory> list, TlDyCategory t)
    {
        // 得到子节点列表
        List<TlDyCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (TlDyCategory tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    private List<TlDyCategory> getChildList(List<TlDyCategory> list, TlDyCategory t)
    {
        List<TlDyCategory> tlist = new ArrayList<TlDyCategory>();
        Iterator<TlDyCategory> it = list.iterator();
        while (it.hasNext())
        {
            TlDyCategory n = (TlDyCategory) it.next();
            if (n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    private boolean hasChild(List<TlDyCategory> list, TlDyCategory t)
    {
        return getChildList(list, t).size() > 0;
    }
}
